<?php

/**
 * UserIdentity.php
 */
class UserIdentity extends CUserIdentity {

    /**
     * @var integer id of logged user
     */
    private $_id;
    private $_model;

    const ERROR_NOT_ACTIVE = 4;

    public function getModel() {
	return $this->_model;
    }

    /**
     * Authenticates username and password
     * @return boolean CUserIdentity::ERROR_NONE if successful authentication
     * @param string $type is type of user. Eg: admin, member
     */
    public function authenticate($type = '') {
	if (strpos($this->username, '@')) {
	    $attribute = 'email';
	} else {
	    $attribute = 'username';
	}
	$user = User::model()->find('LOWER(' . $attribute . ')=? AND type = ?', array(strtolower($this->username), $type));

	if ($user === null) {
	    $this->errorCode = CBaseUserIdentity::ERROR_UNKNOWN_IDENTITY;
	} elseif (!$user->validatePassword($this->password)) {
	    $this->errorCode = CBaseUserIdentity::ERROR_PASSWORD_INVALID;
	} elseif ($user->status != User::STATUS_ACTIVE) {
	    $this->errorCode = self::ERROR_NOT_ACTIVE;
	} else {
	    $this->_model = $user;
	    $this->_id = $user->user_id;
	    $this->username = $user->display_name;
	    $this->errorCode = self::ERROR_NONE;
	}

	return !$this->errorCode;
    }

    /**
     * Creates an authenticated user with no passwords for registration
     * process (checkout)
     * @param string $username
     * @return self
     */
    public static function createAuthenticatedIdentity($id, $username) {
	$identity = new self($username, '');
	$identity->_id = $id;
	$identity->errorCode = self::ERROR_NONE;
	return $identity;
    }

    /**
     *
     * @return integer id of the logged user, null if not set
     */
    public function getId() {
	return $this->_id;
    }

}

